/**
 * Copyright 2002 Cordys R&D B.V. 
 * 
 * This file is part of the Cordys .NET Connector. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 /**
* @author Phani Kavuri
*/
package com.eibus.applicationconnector.ejb;

import java.lang.reflect.Field;
import com.eibus.xml.nom.Node;
import com.eibus.util.logger.CordysLogger;
import static com.eibus.util.logger.Severity.ERROR;


public class UnMarshaller {
    private int classNode;
    private Object mainObject;
    static CordysLogger ejbLogger = CordysLogger.getCordysLogger(UnMarshaller.class);

    private UnMarshaller()
    {}

    public UnMarshaller(int node) {
        classNode = node;
        if (ejbLogger.isDebugEnabled())
        	ejbLogger.debug(classNode);
    }

    public Object unMarshal() throws UnMarshallerException {
        unMarshal(classNode, null);
        return mainObject;
    }

    private void unMarshal(int node, String className) throws UnMarshallerException {
        classNode = node;
        if (ejbLogger.isDebugEnabled())
        	ejbLogger.debug(classNode);
        int parentNode = Node.getParent(Node.getFirstChildElement(classNode));
        if (className==null)
            className = Node.getName(parentNode);
        Class clsObject = null;
        Object myObject = null;
        try {
            clsObject = Class.forName(className);
            myObject = clsObject.newInstance();
        }
        catch(ClassNotFoundException ex) {
            throw new UnMarshallerException(ex.getMessage());
        }
        catch(InstantiationException ex) {
            throw new UnMarshallerException(ex.getMessage());
        }
        catch(IllegalAccessException ex) {
            throw new UnMarshallerException(ex.getMessage());
        }
        if (mainObject == null)
            mainObject = myObject;
        int noOfChildren = Node.getNumChildElements(parentNode);
        int firstChild = Node.getFirstChildElement(classNode);
        for(int i=0;i<noOfChildren;i++) {
            int childrens = Node.getNumChildElements(firstChild);
            String nodeName = Node.getName(firstChild);
            Field myField = null;
            try {
                myField = clsObject.getField(nodeName);
            }
            catch(NoSuchFieldException ex) {
            	ejbLogger.log(ERROR,"Exception by UnMarchaller...."+ex.getMessage());
                throw new UnMarshallerException(ex.getMessage());
            }
            catch(SecurityException ex) {
                throw new UnMarshallerException(ex.getMessage());
            }
            if (childrens != 1) // For Object setting
            {
                UnMarshaller o = new UnMarshaller();
                o.unMarshal(firstChild, myField.getType().getName());
                setValue(myField, o.mainObject, mainObject);
            }
            else    // For property Setting
            {
                String nodeValue = Node.getData(firstChild);
                setValue(myField, nodeValue, myObject);
            }
            firstChild = Node.getNextElement(firstChild);
        }
    }

    private static void setValue(Field myField, Object value, Object myObject)
    throws UnMarshallerException {
        try {
            Class clsObject = myField.getType();
            if (clsObject.isPrimitive()) {
                if (clsObject == Boolean.TYPE)
                    value = Boolean.valueOf(value.toString());
                if (clsObject == Double.TYPE)
                    value = Double.valueOf(value.toString());
                if (clsObject == Integer.TYPE)
                    value = Integer.valueOf(value.toString());
            }
            myField.set(myObject, value);
        }
        catch(IllegalArgumentException ex) {
            throw new UnMarshallerException(ex.getMessage());
        }
        catch(IllegalAccessException ex) {
            throw new UnMarshallerException(ex.getMessage());
        }
    }
}
